﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmPackageCreator : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();
        UnityElement packageid;
        int curDbNum = 0;

        DataTable items = new DataTable();
        string wrnEntMsg = "";
        string curPackageID = "", curPackageIDStamp = "", curSeries = "";
        bool anotherSeries = false;
        bool addNew = false, prcErr = false,Committing = false,
            isViewing = false;
        UnityScript [] food;
        UnityElement curPackage;
        //AutoChecker
        Timer tmr = new Timer();
        int curEdit = -1;

        public frmPackageCreator()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            //Start AutoCheck timer
            txtPrice.TextChanged += new EventHandler(CheckValue);

            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);
            btnAdd.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
            {
                txtRemarks.Focus();
            });
            btnAdd.Click += new EventHandler(btnAdd_Click);
            mnuRemoveEntry.Click += new EventHandler(mnuRemoveEntry_Click);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            btnSave.Visible = false;
            btnAdd.Visible = false;
            btnCancel.Visible = false;
            btnCancel.Click += new EventHandler(btnCancel_Click);
            grdItems.DoubleClick += new EventHandler(grdItems_DoubleClick);
            pnlForm.Enabled = false;
            btnSave.Click +=new EventHandler(btnSave_Click);
            btnAttachDetails.Click += new EventHandler(btnAttachDetails_Click);
            loadData();
        }

        void btnAttachDetails_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count == 1)
            {
                frmPackageDetails frm = new frmPackageDetails(grdItems.SelectedRows[0].Cells[1].Value.ToString(), grdItems.SelectedRows[0].Cells[0].Value.ToString());
                frm.ShowDialog();
            }
        }
        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) t.MethodCall(loadData);
        }
        void btnCancel_Click(object sender, EventArgs e)
        {
            addNew = false;
            foreach (Control ctl in grpDetails.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
            }
           
            btnAdd.Visible = false;
            btnSave.Visible = false;
            btnCancel.Visible = false;
            txtPackageName.Focus();
            loadData();
        }
        void grdItems_DoubleClick(object sender, EventArgs e)
        {
            curEdit = grdItems.SelectedRows[0].Index;
            dat[2].Data_Get(curEdit, out curPackage);

            txtID.Text = curPackage.Data_GetField(0).ToString();
            txtOccasionType.Text = curPackage.Data_GetField(1).ToString();
            txtPackageName.Text = curPackage.Data_GetField(2).ToString();
            txtRemarks.Text = curPackage.Data_GetField(4).ToString();
            txtPrice.Text = curPackage.Data_GetField(3).ToString();

            btnAdd.Visible = false;
            btnSave.Visible = true;
            btnCancel.Visible = true;

            
        }
        void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            Committing = true;
            addNew = false;
            States(false);
            CommitPackage();
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            Committing = true;
            addNew = true;
            States(false);
            CommitPackage();
        }
        void mnuRemoveEntry_Click(object sender, EventArgs e)
        {
           /* if (grdItems.SelectedRows.Count == 0) return;
            DialogResult dlg = MessageBox.Show("The entry will be permanently deleted from the list.\r\n" +
                "Do you wish to continue?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            int sel = grdItems.SelectedRows[0].Index;
            items.Rows[sel].Delete();
            t.MethodCall(CheckEntry);*/
        }
        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }
        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":
                        Committing = false;
                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "loadData":
                        
                        proc.DBPUX_Data_Fetch(out dat);
                        txtOccasionType.Items.Clear();
                        txtOccasionType.Items.AddRange(dat[0].ToList(0));
                        pnlForm.Enabled = true;
                        if (txtOccasionType.Items.Count > 0) txtOccasionType.SelectedIndex = 0;

                        dat[1].Data_Get(0, out packageid);
                        curDbNum = int.Parse(packageid.Data_GetField(0).ToString());
                        curSeries = packageid.Data_GetField(1).ToString();
                        curPackageID = curSeries + (curDbNum).ToString("#0000");
                        if (curDbNum == 999)
                        {
                            curSeries += "P";
                            anotherSeries = true;
                        }
                        curPackageIDStamp = packageid.Data_Stamp;
                        txtID.Text = curPackageID;

                        //Initialize Table Here
                        grdItems.DataSource = dat[2].ToDataTable();
                        grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

                        txtRemarks.Text = "";
                        txtPrice.Text = "";
                        txtSearch.Text = "";
                        txtPackageName.Text = "";
                        txtOccasionType.SelectedIndex = 0;
                        States(true);
                        addNew = false;
                        txtRemarks.Focus();
                        btnAdd.Visible = false;
                        btnSave.Visible = false;
                        btnCancel.Visible = false;
                        txtPackageName.Focus();

                        FormatTable();

                        break;
                    case "LOADDATA":
                    case "COMMIT":
                        loadData();

                        break;
                    
                };
                if (Committing || isViewing) return;
                tmr.Enabled = true;
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch(sender.ToString())
                {
                    case "CheckEntry":
                        lblWarningEntry.Text = wrnEntMsg;

                        if (prcErr)
                            txtPrice.ForeColor = Color.Red;
                        else
                            txtPrice.ForeColor = Color.Black;

                        if (!prcErr)
                            btnAdd.Visible = true;
                        else
                            btnAdd.Visible = false;
                        
                        break;
        
                }
                if (Committing) return;
                tmr.Enabled = true;
            });
        }

        //Operations
        void searchMethod()
        {
            UnityScript u = new UnityScript("LOADDATA", 3);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fPackageID AS 'ID', fOccasion AS 'Occasion', fPackageName AS 'Package Name', fPrice AS 'Price', fRemarks AS 'Remarks', fStamp FROM tblpackageitems WHERE " +
                    "fOccasion LIKE '%{0}%'  OR fPackageName LIKE '%{0}%'", txtSearch.Text));
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void CheckEntry()
        {
            float fprice = 0f;
            string price = txtPrice.Text;
            //Check Price
            if (!float.TryParse(price, out fprice))
            {
                prcErr = true;
                wrnEntMsg = "";
                wrnEntMsg += "Invalid AMOUNT value detected!\r\n";
            }
            else
            {
                prcErr = false;
                if(!prcErr) wrnEntMsg = "";
            }
        }
        void CommitPackage()
        {
            UnityScript u = new UnityScript("COMMIT", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            //Construct Expenses Items
            if (addNew)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblpackageitems(fPackageID, fOccasion, fPackageName, fRemarks, fPrice)",
                    new string[]{
                        txtID.Text,
                        txtOccasionType.Text,
                        txtPackageName.Text.Trim(),
                        txtRemarks.Text,
                        txtPrice.Text
                    });
                u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET fCurNum = fCurNum + 1", "(fID='4')");
            }
            else
            {
                u.Script_Add(Script.DBPUX_UPDATE, string.Format("tblpackageitems SET " +
                    "fOccasion = '{0}', fPackageName='{1}', fPrice='{2}', fRemarks='{3}'", txtOccasionType.Text, txtPackageName.Text.Trim(), txtPrice.Text, txtRemarks.Text),
                    string.Format("(fID='{0}') AND (fStamp='{1}')", curPackage.Data_ID.ToString(), curPackage.Data_Stamp));
            }
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grdItems.Enabled = s;
        }
        
        void loadData()
        {
            UnityScript u = new UnityScript("loadData", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='OCCASION'");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblgenerate WHERE fID ='4'");
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fPackageID AS 'ID', fOccasion AS 'Occasion', fPackageName AS 'Package Name', fPrice AS 'Price', fRemarks AS 'Remarks', fStamp FROM tblpackageitems WHERE " +
                    "fOccasion LIKE '%{0}%'  OR fPackageName LIKE '%{0}%'", txtSearch.Text));
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void FormatTable()
        {
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                string value = grdItems.Rows[i].Cells[3].Value.ToString();
                grdItems.Rows[i].Cells[3].Value = float.Parse(value).ToString("#,#0.00");
            }
        }
        //Printing Module
        
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}